<?php

declare( strict_types = 1 );

namespace App\Common\Model\Base\DataUnit;

use App\Common as com;
use App\Common\Model\Base as nameBase;
use App\Common\Model\Base\DataUnit as nameDataUnit;

class Paginate extends nameDataUnit\Base {

	private int $_currentPage = 1;

	/**
	 * 每页数量
	 * @var int|null
	 */
	private ?int $_listRows = null;

	/**
	 * 每页数量最大值
	 * @var int
	 */
	private int $maxListRows = 100000;

	private bool $isInit = false;

	/**
	 * @param int $page 页码
	 * @param int $listRows 每页数量
	 * @return $this
	 * @throws
	 */
	public function pageParam( int $page, int $listRows ):self {
		$this->setCurrentPage( $page );
		$this->setPageRows( $listRows );
		return $this;
	}

	/**
	 * 获取页码
	 * @return int
	 */
	public function getCurrentPage():int {
		return $this->_currentPage;
	}

	/**
	 * 设置页码
	 * @param int $page
	 * @return $this
	 */
	public function setCurrentPage( int $page ):self {
		$this->_currentPage = $page;
		return $this;
	}

	/**
	 * 获取每页数量
	 * @return int|null [null]所有(未设置)
	 */
	public function getPageRows():?int {
		return $this->_listRows;
	}

	/**
	 * 设置每页数量
	 * @param int $listRows 范围：1~100000
	 * @return $this
	 * @throws
	 */
	public function setPageRows( int $listRows ):self {
		// ...
		if( $listRows === -1 ){
			$listRows = $this->maxListRows;
		}
		if( $listRows < 1 || $listRows > $this->maxListRows ){
			throw com\Lib\Err\Exception::makeOfNew( '每页数量' . com\Lib\Err\Exception\Msg::ofOutOfRange(1, $this->maxListRows, $listRows), com\Lib\Err\Code::$sysFunParamError );
		}
		//
		$this->_listRows = $listRows;
		return $this;
	}

	/**
	 *
	 */
	public function initModelParam(  ) {
		if( $this->getPageRows() > 0 ){
			$this->isInit = true;
			$this->getDataUnit()->goModelQuery()->offset( $this->getPageRows() * ( $this->getCurrentPage() - 1 ) )->limit( $this->getPageRows() );
		}
	}

	/**
	 * 获取总数（注意：需要在select前执行，否则获取失败）
	 * @return int
	 */
	public function getCount(  ):int {
		if( $this->isInit ){
			throw com\Lib\Err\Exception::makeOfNew( 'getCount需要在select前执行，否则获取失败', com\Lib\Err\Code::$sysData );
		}
		return $this->getDataUnit()->goModelQuery()->count();
	}

	/**
	 * 获取分页信息
	 * @param  int $count
	 * @return array
	 */
	public function getPaginateInfo( int $count = null ) {
		// ...
		$info = [];
		//
		if( $count === null ){
			// 检查是否加入了groupBy
/*			if( ! empty( $this->getDataUnit()->goModelQuery()->getQuery()->groups ) ){
				throw com\Lib\Err\Exception::makeOfNew( '获取分页数据前不允许传入groupBy', com\Lib\Err\Code::$sysAssertError );
			}*/
			$info['dataCount'] = $this->getCount();
		}else{
			$info['dataCount'] = $count;
		}
		//
		if( $this->getPageRows() > 0 ){
			$info['pageCount'] = ceil( $info['dataCount'] / $this->getPageRows() );
		}else{
			$info['pageCount'] = 1;
		}
		$info['currentPage'] = $this->getCurrentPage();
		// $info['pageRows'] = $this->getPageRows();
		return $info;
	}

}
